package com.gitee.l0km.xthrift.thrift.protocol;

import static com.gitee.l0km.xthrift.thrift.reflection.FieldSupport.fieldValueOf;
import static com.gitee.l0km.xthrift.thrift.reflection.FieldSupport.setValueOfField;

import org.apache.thrift.protocol.TField;
import org.apache.thrift.protocol.TProtocol;

import com.facebook.swift.codec.internal.TProtocolReader;

/**
 * @author guyadong
 * @since 1.3.2
 *
 */
public class TProtocolSupport {
	private static final String F_CURRENT_FIELD= "currentField";
	/**
	 * 反射方式获取{@code TProtocolReader#currentField}的name字段
	 * @param reader
	 */
	public static String getFieldName(TProtocolReader reader) {
		TField field = fieldValueOf(reader,F_CURRENT_FIELD);
		return field.name;
	}

	/**
	 * 反射方式修改{@code TProtocolReader#currentField}的type字段
	 * @param reader
	 * @param type
	 */
	public static void setTypeOfField(TProtocolReader reader, byte type) {
		TField field = fieldValueOf(reader,F_CURRENT_FIELD);
		setValueOfField(field,"type",type);
	}

	/**
	 * 反射方式修改{@link TProtocolReader#currentField}字段
	 * 
	 * @param reader
	 * @param value
	 */
	public static void setCurrentField(TProtocolReader reader, TField value) {
		setValueOfField(reader,F_CURRENT_FIELD,value);
	}

	static <P extends TProtocol> P fetchInstance(TProtocol protocol,Class<P>clazz) {
		if(clazz.isInstance(protocol)) {
			return clazz.cast(protocol);
		}
		if(protocol instanceof BufferedProtocol) {
			return fetchInstance(((BufferedProtocol)protocol).delegate,clazz);
		}
		return null;
	}
	static boolean isInstanceOf(TProtocol protocol,Class<? extends TProtocol>clazz) {
		return fetchInstance(protocol, clazz) != null;
	}

	public static TJSONProtocolXthrift fetchJSONXthrift(TProtocol protocol) {
		return fetchInstance(protocol,TJSONProtocolXthrift.class);
	}
	public static boolean isJSONXthrift(TProtocol protocol) {
		return isInstanceOf(protocol,TJSONProtocolXthrift.class);
	}
}
